var prefix = jsctx + "/elecLabel";

var label = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                labelName: $('#labelName').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listLabel",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20],
                    pageNumber: 1,
                    sidePagination: "server",
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            labelName: $("#labelName").val().trim()
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'labelId', title: '标签ID', align: 'left', width: '80'},
                        {field: 'labelName', title: '标签名称', width: '80', align: 'center'},
                        {field: 'status', title: '状态', width: '250', align: 'center',
                            formatter: function (value, row, index) {

                                if (value == '1') {
                                    return  '<input class="tgl tgl-skewed" onclick="label.onSwitchChange(' + row.labelId +',0 )" id="cb'+row.labelId+'" type="checkbox"><label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.labelId+'"></label>'
                                } else {
                                    return '<input class="tgl tgl-skeweds"  onclick="label.onSwitchChange(' + row.labelId +',1 )" id="cb'+row.labelId+'" type="checkbox"> <label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.labelId+'"></label>'
                                }
                            }},
                        {field: 'sort', title: '排序', width: '150', align: 'center'},
                        {field: 'createTime', title: '创建时间', width: '200', align: 'center'},
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '300', align: 'center',
                            class: 'operate-td',
                            formatter: function (value, row, index) {
                                var action = '';
                                //var b = '';
                               /* if (StationManager_station_update){

                                }*/
                                action += '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="编辑" onclick="label.editLabel(\''
                                    + row.labelId
                                    + '\')">编辑</a> ';
                                action += '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="删除" onclick="label.deleteLabel(\''
                                    + row.labelId
                                    + '\')">删除</a> ';
                                return action;
                            }
                        }
                    ]
                    , onLoadSuccess: function () {

                    }, onPageChange: function () {

                    }
                });
    }

    function onSwitchChange (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateStatus",
            data: {
                status: state ,
                id: isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
            }
        });
    }


    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function addLabel() {
        location.href = prefix + "/addLabel";
    }
    function editLabel(labelId) {
        location.href = prefix + "/editLabel/"+labelId;
    }
    function deleteLabel(labelId) {
        layer.confirm('确定要删除选中的标签？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteElecLabel",
                type: "post",
                data: {
                    'labelId': labelId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function goBack() {
        location.href = prefix + "/index";
    }


    function exportStation() {
        $.fileDownload(prefix + "/exportStation", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                stationName: $("#labelName").val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function updateForTop(elecStationId, topRemark) {
        if (topRemark != '' && topRemark != 'null') {
            $("#showPlaceTag").val(showPlaceTag)
        }

        $('#exampleModal').modal('show')

        $("#submitForm").unbind("click").bind("click", function () {

            var formData = new FormData();
            formData.append("showPlaceTag", $("#showPlaceTag").val());
            formData.append("elecStationId", elecStationId);
            $.ajax({
                url: prefix + "/updateForTop",
                type: "post",
                data: formData,
                dataType: "json",
                processData: false, // 告诉jQuery不要去处理发送的数据，用于对data参数进行序列化处理 这里必须false
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                    }

                }
            })
        })
    }

  /*  function updateForNoTop(elecStationId) {
        layer.confirm('确定要取消置顶？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateForNoTop",
                type: "post",
                data: {
                    'elecStationId': elecStationId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("取消成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }*/

    function elecStationOut(elecStationId) {
        location.href = prefix + "/elecStationOut/" + elecStationId;
    }

    function tenantOperatorStation(elecStationId) {
        location.href = prefix + "/tenantOperatorStation/" + elecStationId;
    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        addLabel: addLabel,
        editLabel: editLabel,
        onSwitchChange:onSwitchChange,
        exportList: exportList,
        deleteLabel: deleteLabel/*,
        changeStatus: changeStatus,
        deleteStation: deleteStation,
        getArea: getArea,
        getCity: getCity,
        editStation: editStation,
        electricityPrice: electricityPrice,
        detailStation: detailStation,
        jumpDiscountPolicyPage: jumpDiscountPolicyPage,
        exportStation: exportStation,
        elecStationOut: elecStationOut,
        tenantOperatorStation: tenantOperatorStation,
        updateForTop: updateForTop,
        updateForNoTop: updateForNoTop*/
    };
})();

var addElecLabel = (function () {
    function init() {
        validateRule();
    };
    var isajaxsend = true;

    function save() {
        var formData = new FormData($("#frmElecLabel")[0]);
        if (isajaxsend) {
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateElecLabel",
                data: formData,
                processData: false,
                contentType: false,
                // async: false,
                error: function (request) {
                    isajaxsend = true
                    console.log(request)
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        isajaxsend = false
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        isajaxsend = true
                        parent.layer.alert(data.message)
                    }

                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmElecLabel").validate({
            rules: {
                labelName: {
                    required: true
                },
                sort: {
                    required: true
                }
            },
            messages: {
                labelName: {
                    required: icon + "请输入标签名称",
                },
                sort: {
                    required: icon + "请输入标签排序",
                },
            },
            submitHandler: function (form) {
                save();
            }
        })
    }
    return {
        init: init
    };
})();

/*

var elecStationOut = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        /!*if (isajaxsend) {
            var formData = new FormData($("#frmElecStationOut")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateElecStationOut",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }*!/
    }

    function validateRule() {
       /!* var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmElecStationOut").validate({
            rules: {
                outType: {
                    required: true
                },
                printerType: {
                    required: true
                },
                isFreeParking: {
                    required: true
                },
                isNeedNumber: {
                    required: true
                }
            },
            messages: {
                outType: {
                    required: icon + "请选择出场方式"
                },
                printerType: {
                    required: icon + "请选择打印机类型"
                },
                isFreeParking: {
                    required: icon + "请选择是否免费2个小时停车"
                },
                isNeedNumber: {
                    required: icon + "请选择是否必须车牌号"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })*!/
    }

    return {
        init: init
    };
})();
*/
